const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const { User, Class } = require('../models');
const { generateClassCode } = require('../utils/helpers');

// 获取教师的班级列表
router.get('/teacher', auth, async (req, res) => {
  try {
    if (req.user.role !== 'teacher') {
      return res.status(403).json({
        success: false,
        message: '只有教师可以访问此接口'
      });
    }

    const classes = await Class.findAll({
      where: { teacherId: req.user.id },
      include: [{
        model: User,
        attributes: ['id', 'nickname']
      }]
    });

    res.json({
      success: true,
      classes: classes.map(cls => ({
        id: cls.id,
        name: cls.name,
        code: cls.code,
        studentCount: cls.Users.length
      }))
    });

  } catch (error) {
    console.error('Get teacher classes error:', error);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

// 创建班级
router.post('/', auth, async (req, res) => {
  try {
    if (req.user.role !== 'teacher') {
      return res.status(403).json({
        success: false,
        message: '只有教师可以创建班级'
      });
    }

    const { name } = req.body;
    const code = generateClassCode();

    const newClass = await Class.create({
      name,
      code,
      teacherId: req.user.id
    });

    res.json({
      success: true,
      class: {
        id: newClass.id,
        name: newClass.name,
        code: newClass.code
      }
    });

  } catch (error) {
    console.error('Create class error:', error);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

// 学生加入班级
router.post('/join', auth, async (req, res) => {
  try {
    if (req.user.role !== 'student') {
      return res.status(403).json({
        success: false,
        message: '只有学生可以加入班级'
      });
    }

    const { code } = req.body;
    const targetClass = await Class.findOne({ where: { code } });

    if (!targetClass) {
      return res.status(404).json({
        success: false,
        message: '班级不存在'
      });
    }

    // 更新学生的班级
    await req.user.update({ classId: targetClass.id });

    res.json({
      success: true,
      message: '成功加入班级'
    });

  } catch (error) {
    console.error('Join class error:', error);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

module.exports = router;